package cn.edu.hunau.pm.controller;

import cn.edu.hunau.pm.common.ParseBindingResult;
import cn.edu.hunau.pm.common.R;
import cn.edu.hunau.pm.exception.BusinessException;
import cn.edu.hunau.pm.service.UserService;
import cn.edu.hunau.pm.pojo.User;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import cn.edu.hunau.pm.request.LoginUser;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

//@Controller
@RestController//当前的控制层都用异步的交互形式
public class UserManageAction {
    @Autowired
    //@Resource都可以依赖注入
    private UserService userService;
    @PostMapping("/regist")
    public R regist(@RequestBody @Valid LoginUser user, BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            String message= ParseBindingResult.parse(bindingResult);
            throw new BusinessException(100102,message);
        }
        User u=new User();
        u.setNickName(user.getNickName());
        u.setEmail(user.getEmail());
        u.setPwd(user.getPwd());
        userService.regist(u);
        return R.ok();
    }
    @GetMapping("/checkEmail")
    public R checkEmail(String email){
        userService.checkEmailExists(email);
        return R.ok().message("邮箱可以使用");
    }



    @PostMapping("/login")
    //@ResponseBody//底层调用Jackson以json的形式返回数据
    /**
     * @RequestBody将请求参数中的json数据通过Jackson封装成对应的对象
     */
    public R login(@RequestBody @Valid LoginUser user, BindingResult bindingResult)//BindingResult封装了校验器的结果
    {
            if(bindingResult.hasErrors())
            {
                String message= ParseBindingResult.parse(bindingResult);
                throw new BusinessException(100102,message);
            }

            //return R.error().code(100102).message(sb.substring(0,sb.length()-1));

        /**System.out.println("login exe...");
        System.out.println(user);**/


        //return R.ok().data("email",user.getEmail());
        //return R.error().code(100101).message("用户名或者密码错误");
        User u=userService.login(user.getEmail(),user.getPwd());
        return R.ok().data("user",u);
    }
}